package com.nirvana.flatbuffers;


import java.util.regex.Pattern;

/**
 * Copyright (c) 2022 Aoshu.Co.Ltd. All rights reserved.
 *
 * @author :    zhouqichun
 * @create :    2025/11/13 14:36
 * @description :
 **/
public class StringResolver implements IResolve {
    private final Pattern pattern = Pattern.compile("BaseAttr|String|Map\\[.*]");
    @Override
    public boolean canResolve(String propertyType) {
        return pattern.matcher(propertyType).matches();
    }

    @Override
    public String resolve(StringBuilder objectPreContent, String defName, String propertyName, String propertyType) {
        String asString = "";
        if (propertyType.contains("Map")) asString = ".asString";
        objectPreContent.append("""
                                    val %sOffset = builder.createSharedString(m.%s%s)
                    """.formatted(propertyName, propertyName, asString));
        return "%sOffset".formatted(propertyName);
    }

    @Override
    public String resolveVector(StringBuilder objectPreContent, String defName, String propertyName, String propertyType) {
        objectPreContent.append("""
                                val %sOffsets = m.%s.map(builder.createSharedString)
                """.formatted(propertyName, propertyName));
        return "%sOffsets".formatted(propertyName);
    }

    @Override
    public void resolveFbWrapperField(StringBuilder fieldContent, String defName, String comment, String propertyName, String propertyType) {
        if ("String".equals(propertyType)) {
            IResolve.super.resolveFbWrapperField(fieldContent, defName, comment, propertyName, propertyType);
        } else {
            String parseAs = "";
            if (propertyType.contains("Map")) parseAs = ".parseAs[%s]".formatted(propertyType);
            fieldContent.append("""
                    /** %s */
                    private var _%s: %s = _
                    def %s: %s = {
                        if (_%s == null) _%s = raw.%s%s
                        _%s
                    }
                """.formatted(
                    comment,
                    propertyName,
                    propertyType,
                    propertyName,
                    propertyType,
                    propertyName,
                    propertyName,
                    propertyName,
                    parseAs,
                    propertyName
            ));
        }
    }
}
